#ifndef __TCPCONNECTION_H__
#define __TCPCONNECTION_H__

#include "SocketIO.h"
#include <string>
#include "InetAddress.h"
#include "Socket.h"
#include <memory>
#include <functional>

class TcpConnection;

using std::function;
using std::shared_ptr;
using std::string;

using TcpConnectionPtr = shared_ptr<TcpConnection>;
using TcpConnectionCB = function<void(const TcpConnectionPtr &)>;

class EventLoop;

class TcpConnection : public std::enable_shared_from_this<TcpConnection>
{
public:
    explicit TcpConnection(int fd, EventLoop &loop);
    ~TcpConnection();
    void send(const string &msg);
    string receive();

    void setNewConnectionCB(TcpConnectionCB &NewConnectionCB);
    void setMessageCB(TcpConnectionCB &MessageCB);
    void setCloseCB(TcpConnectionCB &CloseCB);

    void handleNewConnectionCB();
    void handleMessageCB();
    void handleCloseCB();
    bool isClose();

    void sendInLoop(const string &msg);
    // 为了方便调试的函数
    string toString();

private:
    // 获取本端地址与对端地址
    InetAddress getLocalAddr();
    InetAddress getPeerAddr();

private:
    SocketIO _SocketIO;
    TcpConnectionCB _NewConnectionCB;
    TcpConnectionCB _MessageCB;
    TcpConnectionCB _CloseCB;
    EventLoop &_loop;

    // 为了调试而加入的三个数据成员
    Socket _sock;
    InetAddress _localAddr;
    InetAddress _peerAddr;
};

#endif